from forest.resource import Resources, Resource, ValidationError

class Service(Resource):
    ''' Enables or disables systemd services.

        Example::

            resources:
              - $: service
                name: sshd

              - $: service
                name: NetworkManager
                enabled: False

        .. describe:: name

            Optional. Name of the service to either enable or disable.

        .. describe:: enabled

            Optional. Boolean value whether to enable or disable the service. (defaults to doing neither)

        .. describe:: depends

           Optional. File resources. If any of them is changed, the service is restarted.
    '''
    __register__ = "service"

    def get_id(self):
        return 'service:' + self.value.get('name')

    def get_name(self):
        # :rtype: basestring
        return self.value.get('name')

    def get_enabled(self):
        #Enable or disable the service (True implies enable)
        #    :rtype: Boolean
        return self.value.get('enabled')

    def get_depends(self):
        return self.value.get('depends', [])

    def validate(self):

        valid_keys = ['type', 'name', 'enabled', 'depends']

        for k, v in self.value.iteritems():
            if k not in valid_keys:
                raise ValidationError("Undefined service option %s" % k)

            if k == 'depends' and not isinstance(v, list):
                raise ValidationError("Depends value must be a list")

        if 'name' not in self.value:
            raise ValidationError("Service name must be defined.")
